require.config({
    paths: {
        'jstree': "../addons/fastflow/plugins/jstree-master/dist/jstree.min",
    },
    shim: {
        'jstree': ['css!../addons/fastflow/plugins/jstree-master/dist/themes/default/style.min.css'],
    },
});

define(['jquery', 'bootstrap', 'backend', 'form', 'jstree', 'template'], function ($, undefined, Backend, Form, undefined, Template) {

    var Controller = {
        selectedNode: null,
        index: function () {
            $('#group_tree').jstree({
                'core': {
                    'themes': {
                        'responsive': false,
                        "icons": true,
                        "dots": false,
                    },
                    'check_callback': true,
                    'data': Config.treeData,
                },
                'types': {
                    'group': {
                        'icon': 'fa fa-navicon text-yellow'
                    },
                    'admin': {
                        'icon': 'fa fa-user text-green'
                    },
                },
                'plugins': ['types', 'themes'],
            });

            $('#group_tree').on("ready.jstree", function (obj, e) {
                if (Config.treeData.length !== 0) {
                    $('#group_tree').jstree('select_node', Config.treeData[0].id);
                }
                Controller.selectedNode = $('#group_tree').jstree(true).get_node(Config.treeData[0].id);
                Controller.api.refreshStampList(Config.treeData[0].scope, Config.treeData[0].data_id);
            });
            $('#group_tree').on("activate_node.jstree", function (obj, e) {
                Controller.selectedNode = e.node;
                Controller.api.refreshStampList(e.node.original.scope, e.node.original.data_id);
            });
            Controller.api.bindListToolBarEvent();
        },
        add: function () {
            if (Config.treeData.length === 0) {
                $('#stamp-toolbar').addClass('hidden');
                $('#group-hint').removeClass('hidden');
            } else {
                $('#group_tree').jstree({
                    'core': {
                        'themes': {
                            'responsive': false,
                            "icons": true,
                            "dots": false,
                        },
                        'check_callback': true,
                        'data': Config.treeData,
                    },
                    'types': {
                        'group': {
                            'icon': 'fa fa-navicon text-yellow'
                        },
                        'admin': {
                            'icon': 'fa fa-user text-green'
                        },
                    },
                    "checkbox": {  // 去除checkbox插件的默认效果
                        keep_selected_style: false,
                    },
                    'plugins': ['types', 'themes', 'checkbox'],
                });
            }
            Controller.api.bindAddEditEvent();
        },
        edit: function () {
            if (Config.treeData.length === 0) {
                $('#stamp-toolbar').addClass('hidden');
                $('#group-hint').removeClass('hidden');
            } else {
                $('#group_tree').jstree({
                    'core': {
                        'themes': {
                            'responsive': false,
                            "icons": true,
                            "dots": false,
                        },
                        'check_callback': true,
                        'data': Config.treeData,
                    },
                    'types': {
                        'group': {
                            'icon': 'fa fa-navicon text-yellow'
                        },
                        'admin': {
                            'icon': 'fa fa-user text-green'
                        },
                    },
                    "checkbox": {  // 去除checkbox插件的默认效果
                        keep_selected_style: false,
                    },
                    'plugins': ['types', 'themes', 'checkbox'],
                });

                $('#group_tree').on("ready.jstree", function (obj, e) {
                    var that = this;
                    Config.auth.forEach(function (item) {
                        var prefix = item.scope == 1 ? 'admin_' : 'group_';
                        var node_id = prefix + item.id;
                        $(that).jstree('select_node', node_id);
                    });
                });
            }
            Controller.api.bindAddEditEvent();
        },
        api: {
            refreshStampList: function (scope, id) {
                var index = layer.load();
                $.ajax({
                    type: "get",
                    url: location.href,
                    data: {
                        scope: scope,
                        id: id,
                    },
                    success: function (data) {
                        if (data['code'] == 1) {
                            $('.stamp-trash').unbind('click');
                            $('.imgProd', '.stamp-list').unbind('click');
                            $('.stamp-edit').unbind('click');
                            var stamps = data['stamps'];
                            var html = Template('itemTpl', {list: stamps});
                            document.getElementById('contenedorCards').innerHTML = html;
                            stamps.length !== 0 ? $('.empty-hint').hide() : $('.empty-hint').show();
                            Controller.api.bindStampTrashEvent();
                            Controller.api.bindStampEditEvent();
                            Controller.api.bindStampThumbnailEvent();
                        } else if (data['code'] == 0) {
                            Toastr.error(data['msg']);
                        }
                        layer.close(index);
                    },
                    error: function (e) {
                        layer.close(index);
                    }
                });
            },
            bindListToolBarEvent: function () {
                $('#add-stamp').click(function (e) {
                    $(this).data('area', ['70%', '70%']);
                    Fast.api.open('fastflow/flow/stamp/add?scope=' + Controller.selectedNode.original.scope + '&id=' + Controller.selectedNode.original.data_id, '添加签章', $(this).data() || {});
                });
                $('#refresh-stamp').click(function (e) {
                    Controller.api.refreshStampList(Controller.selectedNode.original.scope, Controller.selectedNode.original.data_id);
                });
            },
            bindAddEditEvent: function () {
                Form.api.bindevent($("form[role=form]"));
                $('#submit').on('click', function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                    var selectedData = [];
                    if (Config.treeData.length !== 0) {
                        var selectedNodes = $('#group_tree').jstree(true).get_selected(true);
                        selectedNodes.forEach(function (item) {
                            selectedData.push({scope: item.original.scope, id: item.original.data_id});
                        });
                    }
                    $.ajax({
                        type: "post",
                        url: location.href,
                        data: $('#stamp-form').serialize()
                            + '&row[file]=' + $('input[name="row[file]"]').val()
                            + '&row[auth]=' + JSON.stringify(selectedData),
                        success: function (data) {
                            if (data['code'] === 1) {
                                parent.Toastr.success(data['msg']);
                                let index = parent.Layer.getFrameIndex(window.name);
                                parent.Layer.close(index);
                                parent.$('#refresh-stamp', parent.document).trigger('click');
                            } else if (data['code'] === 0) {
                                Toastr.error(data['msg']);
                            }
                        },
                    });
                });
                $('#select-all').on('click', function () {
                    $('#group_tree').jstree('select_all', true);
                });
                $('#deselect-all').on('click', function () {
                    $('#group_tree').jstree('deselect_all', true);
                });
            },
            bindStampTrashEvent: function () {
                $('.stamp-trash').click(function (e) {
                    stampId = $(this).data('id');
                    var that = this;
                    var top = $(that).offset().top - $(window).scrollTop();
                    var left = $(that).offset().left - $(window).scrollLeft() - 160;
                    if (top + 154 > $(window).height()) {
                        top = top - 154;
                    }
                    if ($(window).width() < 480) {
                        top = left = undefined;
                    }
                    Layer.confirm(
                        __('确定删除吗?'),
                        {
                            icon: 3,
                            title: __('Warning'),
                            offset: [top, left],
                            shadeClose: true,
                            btn: [__('OK'), __('Cancel')]
                        },
                        function (index) {
                            $.ajax({
                                type: "post",
                                url: "fastflow/flow/stamp/del",
                                data: {
                                    ids: stampId
                                },
                                success: function (data) {
                                    if (data['code'] == 1) {
                                        Toastr.success('删除成功');
                                        Controller.api.refreshStampList(Controller.selectedNode.original.scope, Controller.selectedNode.original.data_id);
                                    } else if (data['code'] == 0) {
                                        Toastr.error(data['msg']);
                                    }
                                    layer.close(index);
                                },
                                error: function (e) {
                                    layer.close(index);
                                }
                            });
                            Layer.close(index);
                        }
                    );
                });
            },
            bindStampEditEvent: function () {
                $('.stamp-edit').click(function (e) {
                    $(this).data('area', ['70%', '70%']);
                    Fast.api.open('fastflow/flow/stamp/edit?ids=' + $(this).data('id'), '编辑签章', $(this).data() || {});
                });
            },
            bindStampThumbnailEvent: function () {
                $('.imgProd', '#contenedorCards').click(function () {
                    $(this).closest('.wrapper').find('.stamp-edit')[0].click();
                });
            },
        }
    };
    return Controller;
});